﻿/**
*可用地存量分析模块类
@计算方法：用地存量=控规地块各类型总量-已用地地块各类型总量
@WCF请求返回数据格式：[{name:"总面积",data[{name:"用地大类",value:"",data:[{name:"用地中类",value:""}]}]},{name:"剩余面积",data[{name:"用地大类",value:"",data[{name:用地中类,value:""}]}]}]该功能模块既统计了大类，又统计了大类下面的中类（小类合并到中类）
*@module modules.analysis
*@class DCI.LandStock
*@constructor initialize
*@extends Class
*/
define("analysis/landstock", [
    "leaflet",
    "core/dcins",
    "layout/base",
    "data/ajax",
    "libaray/echarts-all",
    "plugins/scrollbar"
], function (L) {

    L.DCI.LandStock = L.DCI.Layout.extend({
        /**
        *类ID
        *@property id
        *@type {String}
        */
        id: "Landstock",
        /**
        *设置选项
        *@property options
        *@type {Object}
        */
        options: {
            city: "",/*可选项，如潍坊市、江阴市,统计表题头显示*/
            region: "",/*统计的区域，如XX街道、XX区*/
            areaMmultiple: 0.000001,/*面积倍数，服务返回数据为平方米，在界面上要显示为平方千米*/
            landType: ""/*用地类型大类名称（如居住用地、交通设施用地）*/
        },
        /**
        *服务器查询返回数据
        *@property _resultData
        *@type {Object}
        */
        _resultData: null,/*服务器查询返回数据*/
        /**
        *区域选择配置
        *@property regionDropSet
        *@type {Object}
        */
        regionDropSet: {
            //区域选择配置
            0: {"RegionID":"001000","RegionName":"全市"}
        },
        /**
        *分析面板html
        *@property _htmlTemplate
        *@type {String}
        */
        _htmlTemplate: '<div class="Landstock-container" >'
            + '<div class="Landstock-contain">'
            + '<div class="Landstock-header">'
            + '<table>'
            + '<tr>'
            + '<td  class="Landstock-td">可用地存量分析</td>'
            + '<td style="text-align:right"></td>'
            + '</tr>'
            + '</table>'
            + '</div>'
            + '<div class="Landstock-selector">'
            + '<small>区域选择:</small>'
            + '<div><select id="Region_Select"></select></div>'
            + '</div>'
            + '<div class="Landstock-content">'
            + '<span class="landstock-charts-tool icon-Viewform"  title="查看详情">查看详细</span>'
            + '<div id="Landstock-chart-bar">'
            + '</div>'
            + '<div id="Landstock-content-table">'
            + '<table class="landstock-charts-table" id="landstock-charts-table">'
            + '<thead></thead>'
            + '<tbody></tbody>'
            + '</table>'
            + '</div>'
            + '</div>'
            + '</div>'
            + '</div>',
        /**
        *可用地存量用地类型详细html
        *@property detailHtml
        *@type {String}
        */
        detailHtml: '<div class="Landstock-detail-contain" style="display:none">'
            + '<div class="Landstock-details-title">'
            + '<span class="icon-return Landstock-details-back"/>'
            + '<p>可用地存量用地类型详细</p>'
            + '</div>'
            + '<div class="Landstock-detail-selector">'
            + '<small>类型选择:</small>'
            + '<div><select  id="Type_Select"></select></div>'
            + '</div>'
            + '<div class="Landstock-detail-content">'
            + '<div id="Landstock-detail-chart-bar">'
            + '</div>'
            + '<div id="Landstock-detail-content-table">'
            + '<table class="landstock-charts-detail-table" id="landstock-charts-detail-table">'
            + '<thead></thead>'
            + '<tbody></tbody>'
            + '</table>'
            + '</div>'
            + '</div>'
            + '</div>',
        getBody: function () {

            return this._container;

        },
        /**
        *初始化
        *@method initialize
        */
        initialize: function () {
            this.ajax = new L.DCI.Ajax();
            this.services = Project_ParamConfig.defaultCoreServiceUrl;
            this._region();
        },
        /**
        *获取行政区划信息
        *@method _region
        *@private
        **/
        _region:function() {
            L.dci.app.services.baseService.getXingzheng({
                context: this,
                success: function (res) {
                    for (var rn in res) {
                        this.regionDropSet[Number(rn)+ 1] = res[rn];
                    }
                    this._creatUi();
                },
                error: function () {
                    L.dci.app.util.dialog.alert("错误提示", "行政区划信息获取失败，请检查该服务。");
                }
            });
        },

        /**
        *创建视图
        *@method _creatUi
        *@private
        */
        _creatUi: function () {
            L.DCI.App.pool.get("rightPanel").clear(0);
            L.DCI.App.pool.get("rightPanel").load(this._htmlTemplate, '可用地存量', 0);
            var container = this._container = $('.Landstock-container')[0];
            $(this._container).append(this.detailHtml);
            this._fillDropFilters(this.regionDropSet);
            this._clickRegister();
            this._charts_bar = echarts.init(document.getElementById('Landstock-chart-bar'));
            this._requestData(this.options.region);
            return this._container;
        },
        /**
        *填充区域选择值
        *@method _fillDropFilters
        *@param data{Array}
        *@private
        */
        _fillDropFilters: function (data) {
            var html = "";
            for (var k in data) {
                var d = data[k];
                var name = d.RegionName;
                html = html + '<option value="' + name + '">' + name + '</option>';
            }

            $(this._container).find('.Landstock-selector select').html(html);
            this.options.region = $(this._container).find('.Landstock-selector option:selected')[0].value;
        },
        /**
        *注册相关点击事件
        *@method _clickRegister
        *@private
        */
        _clickRegister: function () {
            //var buttons = $(this._container).find('.Landstock-selector input[type=button]')[0];
            //L.DomEvent.on(buttons, 'click', this._buttonClick, this);
            var detailbutton = $(this._container).find('.landstock-charts-tool')[0];
            L.DomEvent.on(detailbutton, 'click', this._detailbuttonClick, this);
            var returnBack = $(this._container).find('.Landstock-details-back')[0];
            L.DomEvent.on(returnBack, 'click', this._returnBackClick, this);


            var selects = $(this._container).find('.Landstock-selector select')[0];
            L.DomEvent.on(selects, 'change', this._buttonClick, this);
        },
        /**
        *生成大类用地表格
        *@method _createDataTable
        *@param data{Array}
        *@private
        */
        _createDataTable: function (data) {
            var $head = $(this._container).find('.landstock-charts-table thead');
            var $body = $(this._container).find('.landstock-charts-table tbody');
            var tableHeadHtml = '<tr><td class=>用地性质(大类)</td><td>建设用地存量(平方千米)</td></tr>';
            var bodyhtml = '';
            for (var i = 0; i < data[1].data.length; i++) {
                bodyhtml = bodyhtml + '<tr><td>' + data[1].data[i].name + '</td><td>' + data[1].data[i].value+ '</td></tr>';
            }
            $head.html(tableHeadHtml);
            $body.html(bodyhtml);

        },
        /**
        *填充中类用地属性表格  （如：一类居住地，二类居住地，三类居住地等）
        *@method _createMidDataTable
        *@param data{Array}
        *@private
        */
        _createMidDataTable: function (data) {
            var $head = $(this._container).find('.landstock-charts-detail-table thead');
            var $body = $(this._container).find('.landstock-charts-detail-table tbody');
            var tableHeadHtml = '<tr><td class=>用地性质(中类)</td><td>建设用地存量(平方千米)</td></tr>';
            var bodyhtml = '';
            for (var i = 0; i < data.length; i++) {
                var obj = data[i].data;
                if (data[i].name == "剩余面积") {
                    for (var j = 0; j < obj.length; j++) {
                        bodyhtml += '<tr><td>' + obj[j].name + '</td><td>' + obj[j].value + '</td></tr>';
                    }
                }
            }
            $head.html(tableHeadHtml);
            $body.html(bodyhtml);
            $('.Landstock-detail-content').mCustomScrollbar({
                theme: "minimal-dark"
            });
        },

        /**
        *填充用地大类图表   @用地大类：如居住用地，仓储用地，交通用地等
        *@method _filterChart
        *@param data{Array}
        *@param chart{Object}
        *@private
        */
        _filterChart: function (data, chart) {
            this._resultData = data;
            if (data != null) {
                if (data instanceof Array) {
                    var chartTitle = this._Title("0");
                    var barSeries = [];
                    var legend = [];
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        if (item.name == '总面积') {
                            var series = [];
                            for (var j = 0; j < item.data.length; j++) {
                                var obj = item.data[j];
                                legend[j] = obj.name;
                                series.push({ name: obj.name, value: (obj.value*this.options.areaMmultiple).toFixed(4) });
                            }
                            barSeries.push({ name: item.name, data: series });
                        } else if (item.name == '剩余面积') {
                            var series = [];
                            for (var j = 0; j < item.data.length; j++) {
                                var obj = item.data[j];
                                series.push({ name: obj.name, value: (obj.value* this.options.areaMmultiple).toFixed(4) });
                            }
                            barSeries.push({ name: item.name, data: series });
                        }
                    }
                    this._createDataTable(barSeries);
                    this._barOptionTemplete.title.text = chartTitle + '建设用地存量';
                    this._barOptionTemplete.legend.data = ['总面积', '剩余面积'];
                    this._barOptionTemplete.xAxis[0].data = legend;
                    this._barOptionTemplete.series = barSeries;
                    for (var b = 0; b < this._barOptionTemplete.series.length; b++) {
                        this._barOptionTemplete.series[b].type = 'bar';
                        this._barOptionTemplete.series[b].clickable = true;
                    }

                    chart.setOption(this._barOptionTemplete, true);
                    for (var item in barSeries) {
                        if (barSeries[item].data.length > 0) {
                            chart.hideLoading();
                        }
                    }
                    $(".Landstock-content").mCustomScrollbar({
                        theme: "minimal-dark"
                    });
                    return;
                } else {
                    if (data.error != null) {
                        L.dci.app.util.dialog.error("提示", data.error);
                        return;
                    }
                }
                L.dci.app.util.dialog.error('提示', '获取统计图数据失败');
            }
        },
        /**
        *填充用地中类图表
        *@method _filterMidChart
        *@param data{Array}
        *@private
        */
        _filterMidChart: function (data) {
            if (data != null) {
                if (data instanceof Array) {
                    var chartTile = this._Title("1");
                    var barSeries = [];
                    var legend = [];
                    for (var i = 0; i < data.length; i++) {
                        var item = data[i];
                        for (var j = 0; j < item.data.length; j++) {
                            var obj = item.data[j];
                            if (obj.name == this.options.landType) {
                                
                                if (obj.data.length > 0) {
                                    for (var k = 0; k < obj.data.length; k++) {
                                        legend[k] = obj.data[k].name;
                                        obj.data[k].value = (obj.data[k].value * this.options.areaMmultiple).toFixed(4);
                                    }
                                }
                                barSeries.push({ name: item.name, data: obj.data });
                                break;
                            }
                        }

                    }
                    this._createMidDataTable(barSeries);
                    this._barOptionTemplete.title.text = chartTile + '建设用地存量';
                    this._barOptionTemplete.legend.data = ['总面积', '剩余面积'];
                    this._barOptionTemplete.xAxis[0].data = legend;
                    this._barOptionTemplete.series = barSeries;
                    for (var b = 0; b < this._barOptionTemplete.series.length; b++) {
                        this._barOptionTemplete.series[b].type = 'bar';
                        this._barOptionTemplete.series[b].clickable = true;
                    }

                    this.detail_chart_bar.setOption(this._barOptionTemplete, true);
                    for (var item in barSeries) {
                        if (barSeries[item].data.length > 0) {
                            this.detail_chart_bar.hideLoading();
                        }
                    }
                    
                }

            }


        },
        /**
        *柱状图题头更换事件
        *@method _Title
        *@param model{String}
        *@private
        */
        _Title: function (model) {
            var option = $(this._container).find('.Landstock-selector option:selected')[0];
            if (model == 0) {
                return this.options.region;
            } else return this.options.region + this.options.landType;
        },
        /**
        *查询按钮事件
        *@method _buttonClick
        *@private
        */
        _buttonClick: function () {
            var option = $(this._container).find('option:selected')[0];
            this.options.region = option.value;
            this._requestData(this.options.region);
        },
        /**
        *详细按钮事件
        *@method _detailbuttonClick
        *@param e{Object}
        *@private
        */
        _detailbuttonClick: function (e) {
            $(".Landstock-contain").css({ "display": "none" });
            $(".Landstock-detail-contain").css({ "display": "block" });
            $('.Landstock-details-back').css({ "display": "block" });
            this.detail_chart_bar = echarts.init(document.getElementById("Landstock-detail-chart-bar"));

            var option = $(this._container).find('.Landstock-selector option:selected')[0];
            var title = $('.Landstock-detail-contain').find('p')[0];
            title.innerText = option.value + '可用地存量用地类型详细';
            this._filterTypeSelect();
            var option1 = $(this._container).find('.Landstock-detail-selector option:selected')[0];
            if (option1 != null) {
                this.options.landType = option1.innerText;
            }
            this.detail_chart_bar.showLoading({
                text: '正在加载...',
                backgroundColor: 'rgba(0,0,0,0.5)',
                effect: 'whirling'
            });
            this._filterMidChart(this._resultData);

            var detailSelects = $(this._container).find('.Landstock-detail-selector select')[0];
            L.DomEvent.on(detailSelects, 'change', this._detailButtonClick, this);

            //var detailButton = $(this._container).find('.Landstock-detail-selector input[type=button]')[0];
            //L.DomEvent.on(detailButton, 'click', this._detailButtonClick, this);

        },
        /**
        *返回按钮事件
        *@method _returnBackClick
        *@param e{Object}
        *@private
        */
        _returnBackClick: function (e) {
            $(".Landstock-contain").css({ "display": "block" });
            $(".Landstock-detail-contain").css({ "display": "none" });
        },
        /**
        *填充详细查询类型选择值
        *@method _filterTypeSelect
        *@private
        */
        _filterTypeSelect: function () {
            var typeSelect = '';
            if (this._resultData.length > 0) {

                for (var i = 0; i < this._resultData.length; i++) {
                    var item = this._resultData[i];
                    if (item.name == "总面积") {
                        for (var j = 0; j < item.data.length; j++) {
                            var obj = item.data[j];
                            typeSelect += '<option value="' + obj.name + '">' + obj.name + '</option>';
                        }
                        $(this._container).find('.Landstock-detail-selector select').html(typeSelect);
                        break;
                    }

                }
            }
        },
        /**
        *请求ajax服务
        *@method _requestData
        *@param rg{String}统计的区域
        *@private
        */
        _requestData: function (rg) {
            var url = this.services + "/cpzx/";
            var newUrl = url
                + "static/landuse/stock/" + rg;
            this._charts_bar.showLoading({
                text: '正在加载...',
                backgroundColor: 'rgba(0,0,0,0.5)',
                effect: 'whirling'
            });
            this._resultData = "";
            this.ajax.get(newUrl, null, true, this, function (res) {
                this._filterChart(res, this._charts_bar);
            });
        },
        /**
        *中类用地类型详细按钮查询
        *@method _detailButtonClick
        *@private
        */
        _detailButtonClick: function () {
            var option = $(this._container).find('.Landstock-detail-selector option:selected')[0];
            this.options.landType = option.innerText;
            this._filterMidChart(this._resultData, this.detail_chart_bar);
        },
        /**
        *Bar图表设置 
        *@method _barOptionTemplete
        *@private
        */
        _barOptionTemplete: {
            title: {
                text: ''

            },

            tooltip: {
                trigger: 'axis'
            },

            toolbox: {
                show: false,
                feature: {
                    dataView: { show: true, readOnly: false },
                    saveAsImage: { show: true }
                }
            },

            grid: { borderColo: '#ebebeb' },
            calculable: true,
            legend: { x: 'center', y: '32px', data: null },
            xAxis: [{
                axisLine: {
                    lineStyle: {
                        color: '#d2d2d2',
                        width: 1,
                        type: 'solid'
                    }
                },
                axisLabel: {
                    clickable: true,
                    textStyle: { color: '#acacac' },
                    rotate: 60

                },
                type: 'category',
                data: null
            }],
            yAxis: [{
                axisLine: {
                    lineStyle: {
                        color: '#d2d2d2',
                        width: 1,
                        type: 'solid'
                    }
                },

                type: 'value',
                name: '面积',
                axisLabel: {
                    formatter: function (value) { return (value) + "km²"; }
                }
            }],
            series: null
        },
    });

    return L.DCI.LandStock;
});